package com.ruoyi.ftrl.service.impl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.ftrl.domain.*;
import com.ruoyi.ftrl.domain.Dto.*;
import com.ruoyi.ftrl.mapper.*;
import com.ruoyi.ftrl.service.ITempCacheService;
import com.ruoyi.ftrl.util.HttpUtils;
import com.ruoyi.system.mapper.SysDictDataMapper;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.ftrl.service.IEquipmentDockingService;
import org.apache.http.HttpResponse;

/**
 * 室温实时数据Service业务层处理
 *
 * @author dihang
 * @date 2024-07-09
 */
@Service
public class EquipmentDockingServiceImpl implements IEquipmentDockingService
{
    @Autowired
    private RoomInfoMapper roomInfoMapper;
    @Autowired
    private EquipmentDockingMapper equipmentDockingMapper;
    private final ObjectMapper objectMapper = new ObjectMapper();
    @Autowired
    private CommunityInfoMapper communityInfoMapper;
    @Autowired
    private HeatStationMapper heatStationMapper;
    @Autowired
    private SysDictDataMapper dictDataMapper;
    @Autowired
    private EquipmentInfoMapper equipmentInfoMapper;
    @Autowired
    private ITempCacheService tempCacheService;

    /**
     * 查询室温实时数据
     *
     * @param id 室温实时数据主键
     * @return 室温实时数据
     */
    @Override
    public EquipmentDocking selectEquipmentDockingById(Long id)
    {
        return equipmentDockingMapper.selectEquipmentDockingById(id);
    }

    /**
     * 查询室温实时数据列表
     *
     * @param equipmentDocking 室温实时数据
     * @return 室温实时数据
     */
    @Override
    public List<EquipmentDocking> selectEquipmentDockingList(EquipmentDocking equipmentDocking) {
        // 原有查询逻辑
        List<EquipmentDocking> list = equipmentDockingMapper.selectEquipmentDockingList(equipmentDocking);

        // 批量获取温度统计
        list.forEach(docking -> {
            TempCache tempCache = tempCacheService.getTemperatureByRoom(docking.getRoomNo());
            if (tempCache != null) {
                docking.setAverageTemperature(String.valueOf(tempCache.getAvgTemp()));
                docking.setMaxTem(tempCache.getMaxTemp());
                docking.setMinTem(tempCache.getMinTemp());
            }else {
                docking.setAverageTemperature(String.valueOf(0));
                docking.setMaxTem(BigDecimal.valueOf(0));
                docking.setMinTem(BigDecimal.valueOf(0));
            }
        });

        return list;
    }
//    @Override
//    public List<EquipmentDocking> selectEquipmentDockingList(EquipmentDocking equipmentDocking)
//    {
//        List<EquipmentDocking> list = equipmentDockingMapper.selectEquipmentDockingList(equipmentDocking);
//
//
//
//        for (EquipmentDocking docking : list) {
//                EquipmentDocking temp=equipmentDockingMapper.selectEquipmentDockingTemp(docking.getRoomNo());
//                if (temp!=null){
//                    docking.setAverageTemperature(temp.getAverageTemperature());
//                    docking.setMaxTem(temp.getMaxTem());
//                    docking.setMinTem(temp.getMinTem());
//                }
//
//        }
//
//
//        return list;
//    }

    /**
     * 新增室温实时数据
     *
     * @param equipmentDocking 室温实时数据
     * @return 结果
     */
    @Override
    public int insertEquipmentDocking(EquipmentDocking equipmentDocking)
    {
        equipmentDocking.setCreateTime(DateUtils.getNowDate());
        return equipmentDockingMapper.insertEquipmentDocking(equipmentDocking);
    }

    /**
     * 修改室温实时数据
     *
     * @param equipmentDocking 室温实时数据
     * @return 结果
     */
    @Override
    public int updateEquipmentDocking(EquipmentDocking equipmentDocking)
    {
        equipmentDocking.setUpdateTime(DateUtils.getNowDate());
        return equipmentDockingMapper.updateEquipmentDocking(equipmentDocking);
    }

    /**
     * 批量删除室温实时数据
     *
     * @param ids 需要删除的室温实时数据主键
     * @return 结果
     */
    @Override
    public int deleteEquipmentDockingByIds(Long[] ids)
    {
        return equipmentDockingMapper.deleteEquipmentDockingByIds(ids);
    }

    /**
     * 删除室温实时数据信息
     *
     * @param id 室温实时数据主键
     * @return 结果
     */
    @Override
    public int deleteEquipmentDockingById(Long id)
    {
        return equipmentDockingMapper.deleteEquipmentDockingById(id);
    }

    /**
     * 查询黑蚂蚁实时室温数据
     * @return
     */
    @Override
    public Object selectEquipmentDockingLists() {
//        //每次进行数据拉取时，将上一次拉取的数据设置为历史数据
//        List<EquipmentDocking> list = equipmentDockingMapper.selectEquipmentDockingHistory();
//        for (EquipmentDocking equipmentDocking : list) {
//            equipmentDockingMapper.updateEquipmentDockingHistory(equipmentDocking.getId());
//
//        }
        //获取token值
        String token = null;
        try {
            // 创建URL对象
            URL url = new URL("http://112.33.35.32:2019/api/v1/auth/login");

            // 打开连接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            // 设置请求方法
            conn.setRequestMethod("POST");

            // 设置请求头
            conn.setRequestProperty("Content-Type", "application/json");

            // 启用输入输出流
            conn.setDoOutput(true);

            // 创建请求数据
            String jsonInputString = "{\"name\":\"user_bdftrlzj\",\"password\":\"ABC_123@456\"}";

            // 写入请求数据
            try (OutputStream os = conn.getOutputStream()) {
                byte[] input = jsonInputString.getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            // 获取响应
            int code = conn.getResponseCode();
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            StringBuilder response = new StringBuilder();
            String responseLine;
            while ((responseLine = br.readLine()) != null) {
                response.append(responseLine.trim());
            }

            // 解析JSON响应
            JSONObject jsonResponse = new JSONObject(response.toString());
            if (jsonResponse.getInt("code") == 200) {
                token = jsonResponse.getJSONObject("data").getStr("token");
                System.out.println("Token:" + token);
            } else {
                System.out.println("Error: " + jsonResponse.getStr("message"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        String host = "http://112.33.35.32:2019";
        String path = "/api/v1/data/th/realtime";
        String method = "GET";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        //根据API的要求，定义相对应的Content-Type
        // 添加Authorization token到headers
//        String token = "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJ1c2VyX2JkZnRybHpqIiwiY3JlYXRlZCI6MTcyMTY5ODY0ODAwNSwiZXhwIjoxNzIyMzAzNDQ4fQ.4hvpyEEdC0qUaRx8B148L7JW2PtHzaR8U0A5iyGbENii-DpXw0D3g3PT2EICV1lWhRSQm4mGvn9pnQetowomkg";  // 替换为��的实际token
        headers.put("Authorization", "Bearer " + token);
        headers.put("Content-Type", "application/json;charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        System.err.println("最终Token为："+headers.get("Authorization"));
        querys.put("page", "1");
        querys.put("pageSize", "-1");
//        querys.put("villageNo", "4125");
        querys.put("sortProp", "villageNo");
        querys.put("sortOrder", "0");
//        querys.put("onlineState", "2");
        Object result = new Object();
        try {

            HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
//            System.out.println(response.toString());
            //获取response的body
            result = EntityUtils.toString(response.getEntity());
            System.out.println(result);
            this.insertEquipmentDockingList(result);

        } catch (Exception e) {
            e.printStackTrace();
        }
//        return "操作成功！";
        return result;
    }

    /**
     * 室温实时数据入库
     * @param result
     */
    private void insertEquipmentDockingList(Object result) {


//        ResponseData responseData = objectMapper.readValue(result, ResponseData.class);
//        List<DataItem> items = responseData.getData().getItems();

        JSONObject parse = JSONUtil.parseObj(result);
        ResponseData dockingDto = JSONUtil.toBean(parse, ResponseData.class);
        List<EquipmentDocking> dockingList = dockingDto.getData().getItems();
        for (EquipmentDocking equipmentDocking : dockingList) {
            //查询是否存在上一次最新数据
            EquipmentDocking equipmentDocking1 = equipmentDockingMapper.selectEquipmentDockingByNodeId(equipmentDocking.getNodeId());
            //对于小区名称为十三房舍  电务  机务段东门楼的小区数据不予持久化
            if (equipmentDocking.getVillageName().equals("十三房舍")||equipmentDocking.getVillageName().equals("电务")
                    ||equipmentDocking.getVillageName().equals("机务段东门楼")||equipmentDocking.getVillageName().equals("V7备用")){

            }else {
                if (equipmentDocking1==null||equipmentDocking1.getUploadtime()==null||equipmentDocking.getUploadtime()==null){

                }else {
                    //每次进行新数据存储时，将上一次拉取的不是垃圾的数据设置为历史数据
//                if (equipmentDocking1!=null&&!equipmentDocking1.getUploadtime().equals(equipmentDocking.getUploadtime())){
                    if (equipmentDocking1!=null){
                        Date uploadTime1 = equipmentDocking1.getUploadtime();
                        Date uploadTime2 = equipmentDocking.getUploadtime();
                        // 将 Date 转换为 Instant
                        Instant instant1 = uploadTime1.toInstant();
                        Instant instant2 = uploadTime2.toInstant();
                        Date date = new Date();
                        Instant instant = date.toInstant();//当前时间
                        // 计算两个时间点之间的差异
                        long hoursDifference = Duration.between(instant1, instant2).toHours();
                        long hoursDifferences = Duration.between(instant2, instant).toHours();//当前时间与上次上传时间的间隔
                        //两次上传时间相等 但是设备是在线的（可能是设备上传周期大于一小时）
                        if (equipmentDocking1.getUploadtime().equals(equipmentDocking.getUploadtime())&&hoursDifferences<=24){
                            equipmentDockingMapper.updateEquipmentDockingHistory(equipmentDocking1.getId());
                            insertsEquipmentDocking(equipmentDocking);
                            //两次上传时间不同 证明设备在正常上传数据
                        }else if (!equipmentDocking1.getUploadtime().equals(equipmentDocking.getUploadtime())){
                            equipmentDockingMapper.updateEquipmentDockingHistory(equipmentDocking1.getId());
                            insertsEquipmentDocking(equipmentDocking);
                            //两次上传时间相同 但是上传时间不是24小时之内的 视为掉线设备  将它的上传时间改为这一次的上传时间
                        }else if (equipmentDocking1.getUploadtime().equals(equipmentDocking.getUploadtime())&&hoursDifferences>24){
//                            equipmentDockingMapper.updateEquipmentDockingHistorys(equipmentDocking1.getId(),equipmentDocking1.getUploadtime());
                        }

                    }else{//第一次插入数据
                        insertsEquipmentDocking(equipmentDocking);

                    }
                }


            }

        }

    }

    private void insertsEquipmentDocking(EquipmentDocking equipmentDocking) {
        //根据设备ID查询对应的基础信息，从中获取小区、楼栋、单元、门牌号
        //todo
        EquipmentInfo equipmentInfo = equipmentInfoMapper.selectEquipmentInfoByNodeId(equipmentDocking.getNodeId());
        if (equipmentInfo != null) {
            RoomInfo roomInfo = roomInfoMapper.selectRoomInfoByRoomNo(equipmentDocking.getRoomNo());
            if (roomInfo != null) {
                //小区
                equipmentDocking.setVillageName(roomInfo.getCommunityName());
                //楼栋
                equipmentDocking.setBuildingName(roomInfo.getBuildingName());
                //单元
                equipmentDocking.setUnitName(roomInfo.getUnitName());
                //门牌号
                equipmentDocking.setRoomName(roomInfo.getBuildingName()+"-"+roomInfo.getUnitName()+"-"+roomInfo.getHouseNumber());
                //房间编号
                equipmentDocking.setRoomNo(roomInfo.getRoomNo());
                //供暖状态判断
                if (roomInfo.getHomeType()==null){
                    equipmentDocking.setRoomState("0");
                }else if (roomInfo.getHomeType().equals("4")){
                    equipmentDocking.setRoomState("1");
                }else {
                    equipmentDocking.setRoomState("0");
                }


            }else {
                //小区
                equipmentDocking.setVillageName(equipmentInfo.getCommunityName());
                //楼栋
                equipmentDocking.setBuildingName(equipmentInfo.getBuildingName());
                //单元
                equipmentDocking.setUnitName(equipmentInfo.getUnitName());
                //门牌号
                equipmentDocking.setRoomName(equipmentInfo.getBuildingName()+"-"+equipmentInfo.getUnitName()+"-"+equipmentInfo.getRoomAme());
                //房间编号
                equipmentDocking.setRoomNo(equipmentInfo.getRoomNo());

            }
        }
        if (equipmentDocking.getDeviceStatus()==null){
            equipmentDocking.setDeviceStatus("正常");
        }
        equipmentDocking.setHistory("1");
        equipmentDocking.setManufactor("黑蚂蚁");
        this.insertEquipmentDocking(equipmentDocking);

    }



    public static void main(String[] args) throws IOException {

//        //昨天、今天以及未来两天的天气预报
//        // API密钥
//        String apiKey = "SZcAYSb41uBzL4kau";
//        // API请求URL
//        String url = "https://api.seniverse.com/v3/weather/daily.json?key=SZcAYSb41uBzL4kau&location=baoding&language=zh-Hans&unit=c&start=-1&days=4";
//
//        // 创建HTTP客户端
//        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
//            // 创建HTTP GET请求
//            HttpGet httpGet = new HttpGet(url);
//
//            // 发送请求并获取响应
//            try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
//                HttpEntity entity = response.getEntity();
//                if (entity != null) {
//                    // 将响应内容转换为字符串
//                    String result = EntityUtils.toString(entity);
//                    // 解析JSON响应
//                    JSONObject jsonObject = new JSONObject(result);
//                    JSONArray dailyArray = jsonObject.getJSONArray("results")
//                            .getJSONObject(0)
//                            .getJSONArray("daily");
//
//                    // 遍历解析的天气数据
//                    for (int i = 0; i < dailyArray.size(); i++) {
//                        JSONObject dayWeather = dailyArray.getJSONObject(i);
//                        String date = dayWeather.getStrEscaped("date");
//                        String textDay = dayWeather.getStrEscaped("text_day");
//                        String codeDay = dayWeather.getStrEscaped("code_day");
//                        String textNight = dayWeather.getStrEscaped("text_night");
//                        String codeNight = dayWeather.getStrEscaped("code_night");
//                        String highTemp = dayWeather.getStrEscaped("high");
//                        String lowTemp = dayWeather.getStrEscaped("low");
//                        String precip = dayWeather.getStrEscaped("precip");
//                        String windDirection = dayWeather.getStrEscaped("wind_direction");
//                        String windDirectionDegree = dayWeather.getStrEscaped("wind_direction_degree");
//                        String windSpeed = dayWeather.getStrEscaped("wind_speed");
//                        String windScale = dayWeather.getStrEscaped("wind_scale");  // 使用optString来避免空值报错
//                        String rainfall = dayWeather.getStrEscaped("rainfall");
//                        String humidity = dayWeather.getStrEscaped("humidity");
//
//                        System.out.println("日期: " + date);
//                        System.out.println("白天天气: " + textDay);
//                        System.out.println("白天天气代码: " + codeDay);
//                        System.out.println("夜间天气: " + textNight);
//                        System.out.println("夜间天气代码: " + codeNight);
//                        System.out.println("最高温度: " + highTemp);
//                        System.out.println("最低温度: " + lowTemp);
//                        System.out.println("降水概率: " + precip);
//                        System.out.println("风向: " + windDirection);
//                        System.out.println("风向角度: " + windDirectionDegree);
//                        System.out.println("风速: " + windSpeed);
//                        System.out.println("风力等级: " + windScale);
//                        System.out.println("降水量: " + rainfall);
//                        System.out.println("湿度: " + humidity);
//                        System.out.println("----------------------------------");
//                    }
//                }
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

//          24小时逐时天气
//        String city = "baoding";  // 城市名称
//        List<HourlyForecast> forecasts = getHourlyForecasts(city);
//
//        for (HourlyForecast forecast : forecasts) {
//            System.out.println(forecast);
//        }



//        //实时天气预报
//        // 你的API密钥
//        String apiKey = "SZcAYSb41uBzL4kau";
//        // API请求URL
//        String url = "https://api.seniverse.com/v3/weather/now.json?key=SZcAYSb41uBzL4kau&location=baoding&language=zh-Hans&unit=c";
//
//        // 创建HTTP客户端
//        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
//            // 创建HTTP GET请求
//            HttpGet httpGet = new HttpGet(url);
//
//            // 发送请求并获取响应
//            try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
//                HttpEntity entity = response.getEntity();
//                if (entity != null) {
//                    // 将响应内容转换为字符串
//                    String result = EntityUtils.toString(entity);
//                    // 解析JSON响应
//                    JSONObject jsonObject = new JSONObject(result);
//                    JSONArray resultsArray = jsonObject.getJSONArray("results");
//
//                    if (resultsArray.size() > 0) {
//                        JSONObject locationObject = resultsArray.getJSONObject(0);
//                        JSONObject location = locationObject.getJSONObject("location");
//                        JSONObject now = locationObject.getJSONObject("now");
//
//                        System.out.println("城市ID: " + location.getStrEscaped("id"));
//                        System.out.println("城市名称: " + location.getStrEscaped("name"));
//                        System.out.println("国家: " + location.getStrEscaped("country"));
//                        System.out.println("路径: " + location.getStrEscaped("path"));
//                        System.out.println("时区: " + location.getStrEscaped("timezone"));
//                        System.out.println("时区偏移: " + location.getStrEscaped("timezone_offset"));
//
//                        System.out.println("实况天气:");
//                        System.out.println("  天气现象: " + now.getStrEscaped("text"));
//                        System.out.println("  天气代码: " + now.getStrEscaped("code"));
//                        System.out.println("  温度: " + now.getStrEscaped("temperature"));
//                        System.out.println("  体感温度: " + now.getStrEscaped("feels_like"));
//                        System.out.println("  气压: " + now.getStrEscaped("pressure"));
//                        System.out.println("  湿度: " + now.getStrEscaped("humidity"));
//                        System.out.println("  能见度: " + now.getStrEscaped("visibility"));
//                        System.out.println("  风向: " + now.getStrEscaped("wind_direction"));
//                        System.out.println("  风向角度: " + now.getStrEscaped("wind_direction_degree"));
//                        System.out.println("  风速: " + now.getStrEscaped("wind_speed"));
//                        System.out.println("  风力等级: " + now.getStrEscaped("wind_scale"));
//                        System.out.println("  云量: " + now.getStrEscaped("clouds", "N/A")); // 使用 optString 以避免空值报错
//                        System.out.println("  露点温度: " + now.getStrEscaped("dew_point", "N/A")); // 使用 optString 以避免空值报错
//
//                        System.out.println("数据更新时间（本地时间）: " + locationObject.getStrEscaped("last_update"));
//                    }
//                }
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

        //获取token值
        String token = null;
        try {
            // 创建URL对象
            URL url = new URL("http://112.33.35.32:2019/api/v1/auth/login");

            // 打开连接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            // 设置请求方法
            conn.setRequestMethod("POST");

            // 设置请求头
            conn.setRequestProperty("Content-Type", "application/json");

            // 启用输入输出流
            conn.setDoOutput(true);

            // 创建请求数据
            String jsonInputString = "{\"name\":\"api_bdft\",\"password\":\"123456\"}";

            // 写入请求数据
            try (OutputStream os = conn.getOutputStream()) {
                byte[] input = jsonInputString.getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            // 获取响应
            int code = conn.getResponseCode();
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            StringBuilder response = new StringBuilder();
            String responseLine;
            while ((responseLine = br.readLine()) != null) {
                response.append(responseLine.trim());
            }

            // 解析JSON响应
            JSONObject jsonResponse = new JSONObject(response.toString());
            if (jsonResponse.getInt("code") == 200) {
                token = jsonResponse.getJSONObject("data").getStr("token");
                System.out.println("Token:" + token);
            } else {
                System.out.println("Error: " + jsonResponse.getStr("message"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }




    private static final String API_KEY = "SZcAYSb41uBzL4kau";
    private static final String API_URL = "https://api.seniverse.com/v3/weather/hourly.json";

    public static List<HourlyForecast> getHourlyForecasts(String city) throws IOException {
        String url = API_URL + "?key=" + API_KEY + "&location=" + city + "&language=zh-Hans&unit=c&start=0&hours=24";

        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet request = new HttpGet(url);

        try (CloseableHttpResponse response = httpClient.execute(request)) {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String result = EntityUtils.toString(entity);
                System.out.println("API Response: " + result); // 打印响应内容
                return parseHourlyForecasts(result);
            }
        }
        return new ArrayList<>();
    }

    public static List<HourlyForecast> parseHourlyForecasts(String jsonData) {
        List<HourlyForecast> forecasts = new ArrayList<>();

        JsonObject jsonObject = JsonParser.parseString(jsonData).getAsJsonObject();
        JsonArray resultsArray = jsonObject.getAsJsonArray("results");

        if (resultsArray == null || resultsArray.size() == 0) {
            System.err.println("No 'results' array found in response.");
            return forecasts;
        }

        JsonObject firstResult = resultsArray.get(0).getAsJsonObject();
        JsonArray hourlyArray = firstResult.getAsJsonArray("hourly");

        if (hourlyArray == null || hourlyArray.size() == 0) {
            System.err.println("No 'hourly' array found in first result.");
            return forecasts;
        }

        for (int i = 0; i < hourlyArray.size(); i++) {
            JsonObject hourObject = hourlyArray.get(i).getAsJsonObject();
            String time = hourObject.get("time").getAsString();
            String temperature = hourObject.get("temperature").getAsString();
            String weatherText = hourObject.get("text").getAsString();

            HourlyForecast forecast = new HourlyForecast(time, temperature, weatherText);
            forecasts.add(forecast);
        }

        return forecasts;
    }

    /**
     * 查询室温历史数据列表
     * @param equipmentDocking
     * @return
     */
    @Override
    public List<EquipmentDocking> selectEquipmentDockingListHistory(EquipmentDocking equipmentDocking) {
        //计算3天内的最高温度和最低温度
        //todo
        return equipmentDockingMapper.selectHistoryEquipmentDocking(equipmentDocking);
    }

    /**
     * 数据分析（大屏）
     * @param dateDto
     * @return
     */
    @Override
    public List<DailyTemperatureDto> selectEquipmentDockingByIds(DateDto dateDto) throws ParseException {
        List<DailyTemperatureDto> resultList = new ArrayList<>();
        List<String> roomNos = dateDto.getRoomNos();

        // 处理时间参数
        Date startTime;
        Date endTime;
        if (dateDto.getParams() != null) {
            // 解析前端传递的时间
            String beginRecordDate = (String) dateDto.getParams().get("beginRecordDate");
            String endRecordDate = (String) dateDto.getParams().get("endRecordDate");
            startTime = parseDate(beginRecordDate, false); // 开始时间 00:00:00
            endTime = parseDate(endRecordDate, true);      // 结束时间 23:59:59
        } else {
//            // 默认查询过去24小时
//            Calendar cal = Calendar.getInstance();
//            endTime = cal.getTime();
//            cal.add(Calendar.HOUR, -24);
//            startTime = cal.getTime();
            // 默认查询前一天的完整24小时
            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.DAY_OF_MONTH, -1); // 先把日期调到前一天

            // 设置前一天的结束时间 23:59:59
            cal.set(Calendar.HOUR_OF_DAY, 23);
            cal.set(Calendar.MINUTE, 59);
            cal.set(Calendar.SECOND, 59);
            endTime = cal.getTime();

            // 设置前一天的开始时间 00:00:00
            cal.set(Calendar.HOUR_OF_DAY, 0);
            cal.set(Calendar.MINUTE, 0);
            cal.set(Calendar.SECOND, 0);
            startTime = cal.getTime();
        }

        // 遍历每个房间查询数据
        for (String roomNo : roomNos) {
            // 查询每日温度数据
            List<DailyTemperatureDto> dailyTemps = equipmentDockingMapper.selectDailyTemperature(
                    roomNo, startTime, endTime
            );

            // 填充公共信息（小区、热力站等）
            if (!dailyTemps.isEmpty()) {
                // 获取房间基础信息（只需查一次）
                RoomInfo roomInfo = roomInfoMapper.selectRoomInfoByRoomNo(roomNo);
                CommunityInfo communityInfo = communityInfoMapper.selectCommunityInfoByName(
                       roomInfo.getCommunityName() // 假设 village_name 在数据中
                );

                HeatStation heatStation = null;
                if (communityInfo != null) {
                    heatStation = heatStationMapper.selectHeatStationById(communityInfo.getHeatId());
                }

                // 填充公共字段
                for (DailyTemperatureDto dto : dailyTemps) {
                    // 房间信息
                    dto.setRoomNo(roomNo);
                    dto.setRoomInfo(buildRoomInfo(roomInfo)); // 拼接楼栋+单元+房间
                    //小区名称
                    dto.setVillageName(roomInfo.getCommunityName());
                    dto.setBuildingName(roomInfo.getBuildingName());
                    dto.setUnitName(roomInfo.getUnitName());

                    // 户型
                    dto.setHomeType(roomInfo.getHomeType());

                    // 换热站
                    if (heatStation != null) {
                        dto.setHeatName(heatStation.getName());
                    }
                    //

                    resultList.add(dto);
                }
            }
        }

        return resultList;
    }

    // 时间解析工具方法
    private Date parseDate(String dateStr, boolean isEndOfDay) throws ParseException {
        if (dateStr == null) return null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = sdf.parse(dateStr);
        if (isEndOfDay) {
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            cal.set(Calendar.HOUR_OF_DAY, 23);
            cal.set(Calendar.MINUTE, 59);
            cal.set(Calendar.SECOND, 59);
            return cal.getTime();
        }
        return date;
    }

    // 构建房间信息字符串
    private String buildRoomInfo(RoomInfo roomInfo) {
        if (roomInfo == null) return "";
        return roomInfo.getBuildingName() + "-" +
                roomInfo.getUnitName() + "-" +
                roomInfo.getHouseNumber();
    }

//    @Override
//    public List<EquipmentDocking> selectEquipmentDockingByIds(DateDto dateDto) {
//        List<EquipmentDocking> list = new ArrayList<>();
//        List<String> roomNos = dateDto.getRoomNos();
//
//        // 处理时间参数
//        Date startTime = null;
//        Date endTime = null;
//
//        // 从 params 中获取时间
//        if (dateDto.getParams() != null) {
//            String beginRecordDate = (String) dateDto.getParams().get("beginRecordDate");
//            String endRecordDate = (String) dateDto.getParams().get("endRecordDate");
//
//            if (beginRecordDate != null && endRecordDate != null) {
//                try {
//                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//                    startTime = sdf.parse(beginRecordDate);
//                    // 设置结束时间为当天的23:59:59
//                    Calendar cal = Calendar.getInstance();
//                    cal.setTime(sdf.parse(endRecordDate));
//                    cal.set(Calendar.HOUR_OF_DAY, 23);
//                    cal.set(Calendar.MINUTE, 59);
//                    cal.set(Calendar.SECOND, 59);
//                    endTime = cal.getTime();
//                } catch (ParseException ignored) {
//
//                }
//            }
//        }
//
//        // 如果没有时间参数，使用默认的一天时间范围
//        if (startTime == null || endTime == null) {
//            Calendar cal = Calendar.getInstance();
//            endTime = cal.getTime();
//            cal.add(Calendar.DAY_OF_MONTH, -1);
//            startTime = cal.getTime();
//        }
//
//        // 遍历房间号进行查询
//        for (String roomNo : roomNos) {
//            EquipmentDocking equipmentDocking;
//
//            // 根据时间范围查询数据
//            equipmentDocking = equipmentDockingMapper.selectEquipmentCountDockingList(roomNo, startTime, endTime);
//
//            if (equipmentDocking != null) {
//                // 设置房间名称（楼栋+房间）
//                equipmentDocking.setRoomName(equipmentDocking.getRoomName());
//
//                // 设置户型
//                RoomInfo roomInfo = roomInfoMapper.selectRoomInfoByRoomNo(roomNo);
//                if (roomInfo != null) {
//                    equipmentDocking.setHomeType(roomInfo.getHomeType());
//                }
//
//                // 设置小区和热力站信息
//                CommunityInfo communityInfo = communityInfoMapper.selectCommunityInfoByName(
//                        equipmentDocking.getVillageName());
//                if (communityInfo != null) {
//                    HeatStation heatStation = heatStationMapper.selectHeatStationById(
//                            communityInfo.getHeatId());
//                    if (heatStation != null) {
//                        // 设置班组信息
//                        if (heatStation.getCrew() != null) {
//                            String label = dictDataMapper.selectDictLabel("crew",
//                                    heatStation.getCrew());
//                            equipmentDocking.setCrew(label);
//                        }
//                        equipmentDocking.setHeatName(heatStation.getName());
//                    }
//                }
//
//                list.add(equipmentDocking);
//            }
//        }
//
//        return list;
//    }

    /**
     * 历史数据查询（大屏展示）
     * @param
     * @return
     */
    @Override
    public List<EquipmentDocking> selectEquipmentDockingByroomNos(DateDto dateDto) {

        Map<String, Object> params = new HashMap<>();
        params.put("roomNos", dateDto.getRoomNos());
        params.put("beginRecordDate", dateDto.getBeginRecordDate());
        params.put("endRecordDate", dateDto.getEndRecordDate());
        return equipmentDockingMapper.selectEquipmentCountDockingByRoomNoss(params);

//        List<EquipmentDocking> list=new ArrayList<>();
//        List<String> roomNos = dateDto.getRoomNos();
//        //默认查询一周内的历史数据
//        if (dateDto.getStartTime()==null && dateDto.getEndTime()==null){
//            for (String roomNo : roomNos) {
//                List<EquipmentDocking> equipmentDocking= equipmentDockingMapper.selectEquipmentCountDockingByRoomNo(roomNo);
//                list.addAll(equipmentDocking);
//
//            }
//            return list;
//        }//当有开始与结束的时间情况下
//        for (String roomNo : roomNos) {
//            List<EquipmentDocking> equipmentDockings= equipmentDockingMapper.selectEquipmentCountDockingByRoomNos(roomNo,dateDto.getStartTime(), dateDto.getEndTime());
//            list.addAll(equipmentDockings);
//        }
//
//        return list;
//        PageHelper.startPage(1, 10); // 设置分页
    }

    /**
     * 室温分析界面温度最高值，最低值，平均值
     * @return
     */
    @Override
    public EquipmentDocking selectEquipmentDockingCount() {
       EquipmentDocking equipmentDocking= equipmentDockingMapper.selectEquipmentCountDockingCount();
        return equipmentDocking;
    }

    /**
     * 历史曲线（大屏展示 以天为单位）
     * @param dateDto
     * @return
     */
    @Override
    public TempDto selectEquipmentDockingCurve(DateDto dateDto) {

//        TempDto tempDto = new TempDto();
//
//        List<String> roomNos = dateDto.getRoomNos();
//        LocalDate startDate;
//        LocalDate endDate;
//        List<Long>temps=new ArrayList<>();
//        if (dateDto.getStartTime() == null && dateDto.getEndTime() == null) {
//            temps=weatherMapper.selectWeeklyAverageTemperature();
//            // 没有输入开始时间和结束时间，默认查询过去一周的数据
//            LocalDate today = LocalDate.now();
//            endDate = today;
//            startDate = today.minusDays(6);
//        } else {
//
//            // 输入了开始时间和结束时间
//            endDate = dateDto.getEndTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
//            startDate = dateDto.getStartTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
//            temps=weatherMapper.selectWeatherTimess(dateDto.getStartTime(),dateDto.getEndTime());
//        }
//
//        // 构建日期列表
//        List<Date> dates = new ArrayList<>();
//        for (LocalDate date = startDate; !date.isAfter(endDate); date = date.plusDays(1)) {
//            dates.add(Date.from(date.atStartOfDay(ZoneId.systemDefault()).toInstant()));
//        }
//        tempDto.setTime(dates);
//
//        List<String> names = new ArrayList<>();
//        names.add("平均室外温度");
//        List<Category> categoryList = new ArrayList<>();
//
//        for (String roomNo : roomNos) {
//            EquipmentDocking equipmentDocking = equipmentDockingMapper.selectEquipmentCountDockingByRoom(roomNo);
//            names.add(equipmentDocking.getRoomName());
//
//            Category category = new Category();
//            category.setName(equipmentDocking.getRoomName());
//            category.setType("line");
//            category.setData(new ArrayList<>());
//
//            for (Date date : dates) {
//                Map<String, Object> params = new HashMap<>();
//                params.put("roomNo", roomNo);
//                String formattedDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate().toString();
//                params.put("date", formattedDate);
//
//                Long temperature = equipmentDockingMapper.selectEquipmentCountDockingByTimes(params);
//                if (temperature != null) {
//                    category.getData().add(temperature);
//                } else {
//                    category.getData().add(0l);
//                }
//            }
//            categoryList.add(category);
//        }
//
//        // 添加室外温度曲线
//        Category category1 = new Category();
//        category1.setName("平均室外温度");
//        category1.setType("line");
////        List<Double> temps = weatherMapper.selectWeather();
//        category1.setData(temps);
//        categoryList.add(category1);
//
//        tempDto.setName(names);
//        tempDto.setCategoryList(categoryList);

        return null;
    }

    /**
     * 历史曲线（大屏展示 以小时为单位）
     * @param dateDto
     * @return
     */
    public TempDto1 selectEquipmentDockingCurveHour(DateDto dateDto) {
        TempDto1 tempDto = new TempDto1();
        List<String> roomNos = dateDto.getRoomNos();
        LocalDateTime startDateTime;
        LocalDateTime endDateTime;
        List<Double> temps = new ArrayList<>();

        if (dateDto.getStartTime() == null && dateDto.getEndTime() == null) {
            // 默认查询过去24小时内的每个小时
            LocalDateTime now = LocalDateTime.now();
            endDateTime = now.withMinute(0).withSecond(0).withNano(0); // 当前整点
            startDateTime = endDateTime.minusDays(1);
            temps = weatherMapper.selectHourlyAverageTemperature(
                    java.sql.Timestamp.valueOf(startDateTime),
                    java.sql.Timestamp.valueOf(endDateTime)
            );

        } else {
            // 使用输入的开始时间和结束时间
            startDateTime = dateDto.getStartTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime().withMinute(0).withSecond(0).withNano(0);
            endDateTime = dateDto.getEndTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime().withMinute(0).withSecond(0).withNano(0);
            temps = weatherMapper.selectWeatherTimes(
                    java.sql.Timestamp.valueOf(startDateTime),
                    java.sql.Timestamp.valueOf(endDateTime)
            );
        }

        // 构建小时列表
        List<Date> dates = new ArrayList<>();
        for (LocalDateTime dateTime = startDateTime; !dateTime.isAfter(endDateTime); dateTime = dateTime.plusHours(1)) {
            dates.add(Date.from(dateTime.atZone(ZoneId.systemDefault()).toInstant()));
        }
        tempDto.setTime(dates);

        List<String> names = new ArrayList<>();
        names.add("平均室外温度");
        List<Category1> categoryList = new ArrayList<>();

        for (String roomNo : roomNos) {
            EquipmentDocking equipmentDocking = equipmentDockingMapper.selectEquipmentCountDockingByRoom(roomNo);
            names.add(equipmentDocking.getVillageName()+"-"+equipmentDocking.getRoomName());

            Category1 category = new Category1();
            category.setName(equipmentDocking.getVillageName()+"-"+equipmentDocking.getRoomName());
            category.setType("line");
            category.setData(new ArrayList<>());

            for (Date date : dates) {
                LocalDateTime hourDateTime = date.toInstant()
                        .atZone(ZoneId.systemDefault())
                        .toLocalDateTime();
                Map<String, Object> params = new HashMap<>();
//                params.put("roomNo", roomNo);
//                params.put("startTime", Timestamp.valueOf(startDateTime));
//                params.put("endTime", Timestamp.valueOf(endDateTime));
                params.put("roomNo", roomNo);
                params.put("startTime", Timestamp.valueOf(hourDateTime));
                params.put("endTime", Timestamp.valueOf(hourDateTime.plusHours(1)));

                Double temperature = equipmentDockingMapper.selectEquipmentCountDockingByTimes(params);
                if (temperature != null) {
                    category.getData().add(temperature);
                } else {
                    category.getData().add(0.0);
                }
            }
            categoryList.add(category);
        }

        // 添加室外温度曲线
        Category1 category1 = new Category1();
        category1.setName("平均室外温度");
        category1.setType("line");
        category1.setData(temps);
        categoryList.add(category1);

          // 补充缺失的数据点
        for (int i = 0; i < dates.size(); i++) {
            if (i < temps.size()) {
                temps.add(temps.get(i));
            } else {
                // 使用最后一个有效值或默认值
                temps.add(temps.isEmpty() ? 0.0 : temps.get(temps.size() - 1));
            }
        }

        tempDto.setName(names);
        tempDto.setCategoryList(categoryList);

        return tempDto;
    }

    /**
     * 室温分析户主信息（大屏展示）
     */
    @Override
    public EquipmentDocking selectEquipmentDockingPerson(String roomNo) {
        EquipmentDocking equipmentDocking = equipmentDockingMapper.selectEquipmentCountDockingByRoom(roomNo);
        RoomInfo roomInfo=roomInfoMapper.selectRoomInfoByPhone(equipmentDocking.getTelephone());
        if (roomInfo!=null){
            equipmentDocking.setArea(roomInfo.getArea());
            equipmentDocking.setUnitName(roomInfo.getUnitName());
            equipmentDocking.setHeat_area(roomInfo.getUseAre());
            //户型
           equipmentDocking.setHomeType(roomInfo.getHomeType());
           //建筑类型
            equipmentDocking.setBuildingType(roomInfo.getBuildingType());

        }

        return equipmentDocking;
    }

    /**
     * 查询单个房间室温历史数据列表
     */
    @Override
    public List<EquipmentDocking> selectEquipmentDockingListHistoryRoom(String  roomNo,Date startTime,Date endTime) {
        if (startTime==null && endTime==null){
            //默认查询所有历史数据
            return equipmentDockingMapper.selectEquipmentCountDockingByRooms(roomNo);
        }
      return equipmentDockingMapper.selectEquipmentCountDockingByRoomNos(roomNo,startTime,endTime);


    }
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd HH:mm");

    /**
     * 驾驶舱小区历史曲线（最新大屏展示）
     */
    @Override
    public CurveDto selectEquipmentDockingStance(TempsDtos tempsDto) {
        CurveDto tempDto = new CurveDto();
        List<String> nameList = tempsDto.getNames();
        List<Categorys> categoryList = new ArrayList<>();

        try {
            // 处理时间参数（保持原有逻辑）
            String startTime = tempsDto.getStartTime();
            String endTime = tempsDto.getEndTime();

            if (startTime == null || endTime == null) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Calendar cal = Calendar.getInstance();
                endTime = sdf.format(cal.getTime());
                cal.add(Calendar.DAY_OF_MONTH, -3);
                startTime = sdf.format(cal.getTime());
            } else {
                endTime = endTime + " 23:59:59";
                startTime = startTime + " 00:00:00";
            }

            // 获取时间轴（保持原有逻辑）
            List<String> timeAxis = equipmentDockingMapper.selectTimeAxiss(startTime, endTime);
            tempDto.setTime(timeAxis);

            // 添加室外温度曲线（保持原有逻辑）
            Categorys outdoorCategory = new Categorys();
            outdoorCategory.setName("平均室外温度");
            outdoorCategory.setType("line");
            List<Double> outdoorTemps = weatherMapper.selectWeatherTime(startTime, endTime);
            outdoorCategory.setData(outdoorTemps);
            categoryList.add(outdoorCategory);

            // 参数准备
            Map<String, Object> params = new HashMap<>();
            params.put("stationNames", nameList);
            params.put("startTime", startTime);
            params.put("endTime", endTime);

            // 执行查询（返回每小时每个热力站的平均温度）
            List<StationTemperature> stationTemps = equipmentDockingMapper.selectTempTimesBatch(params);

            // --- 核心修改：按热力站分组，合并温度数据 ---
            Map<String, List<Double>> stationTempMap = new HashMap<>();
            for (StationTemperature temp : stationTemps) {
                if (temp != null && temp.getStationName() != null) {
                    String stationName = temp.getStationName();
                    Double avgTemp = temp.getAvgTemp();

                    // 按热力站名称分组，收集温度值
                    if (!stationTempMap.containsKey(stationName)) {
                        stationTempMap.put(stationName, new ArrayList<>());
                    }
                    if (avgTemp != null) {
                        stationTempMap.get(stationName).add(avgTemp);
                    }
                }
            }

            // 构建 Categorys 对象列表
            for (Map.Entry<String, List<Double>> entry : stationTempMap.entrySet()) {
                Categorys category = new Categorys();
                category.setName(entry.getKey());      // 热力站名称
                category.setType("line");
                category.setData(entry.getValue());    // 温度列表
                categoryList.add(category);
            }

            // 设置热力站名称列表（去重）
            List<String> stationNames = new ArrayList<>(stationTempMap.keySet());
            stationNames.add("平均室外温度");
            tempDto.setName(stationNames);            // 设置 names
            tempDto.setCategoryList(categoryList);   // 设置 categoryList

        } catch (Exception e) {
            e.printStackTrace();
        }

        return tempDto;
    }

//    @Override
//    public CurveDto selectEquipmentDockingStance(TempsDtos tempsDto) {
//
//        CurveDto tempDto = new CurveDto();
//        List<String> nameList = tempsDto.getNames();
//        List<String> names = new ArrayList<>();
//        List<Categorys> categoryList = new ArrayList<>();
//
//        try {
//            // 处理时间参数
//            String startTime = tempsDto.getStartTime();
//            String endTime = tempsDto.getEndTime();
//
//            if (startTime == null || endTime == null) {
//                // 默认查询过去一周
//                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                Calendar cal = Calendar.getInstance();
//                endTime = sdf.format(cal.getTime());
//                cal.add(Calendar.DAY_OF_MONTH, -3);
//                startTime = sdf.format(cal.getTime());
//            } else {
//                // 确保结束时间包含完整的一天
//                endTime = endTime + " 23:59:59";
//                startTime = startTime + " 00:00:00";
//            }
//
//            // 获取时间轴
//            List<String> timeAxis = equipmentDockingMapper.selectTimeAxiss(startTime, endTime);
//            tempDto.setTime(timeAxis);
//
//            // 添加室外温度曲线
//            Categorys outdoorCategory = new Categorys();
//            outdoorCategory.setName("平均室外温度");
//            outdoorCategory.setType("line");
//            List<Double> outdoorTemps = weatherMapper.selectWeatherTime(startTime, endTime);
//            outdoorCategory.setData(outdoorTemps);
//            categoryList.add(outdoorCategory);
//
//            // 处理每个热力站的数据
//            for (String stationName : nameList) {
//                names.add(stationName);
//
//                Categorys category = new Categorys();
//                category.setName(stationName);
//                category.setType("line");
//
//                // 查询该热力站下所有小区的平均温度
//                List<Double> temps = equipmentDockingMapper.selectTempTimes(stationName, startTime, endTime);
//
//                // 如果数据为空，填充默认值或null
//                if (temps == null || temps.isEmpty()) {
//                    temps = timeAxis.stream()
//                            .map(time -> 0.0)
//                            .collect(Collectors.toList());
//                }
//
//                category.setData(temps);
//                categoryList.add(category);
//
//
//            }
//
//            names.add("平均室外温度");
//            tempDto.setName(names);
//            tempDto.setCategoryList(categoryList);
//
//        } catch (Exception ignored) {
//
//        }
//
//        return tempDto;
//    }

    @Autowired
private WeatherMapper weatherMapper;
    /**
     * 驾驶舱小区历史曲线（大屏展示）
     */
//    @Override
    public TempDto selectEquipmentDockingStances(TempsDto tempsDto) {
        TempDto tempDto = new TempDto();

        List<String> nameList = tempsDto.getNames();
        LocalDate startDate;
        LocalDate endDate;

        if (tempsDto.getStartTime() == null && tempsDto.getEndTime() == null) {
            // 没有输入开始时间和结束时间，默认查询过去一周的数据
            LocalDate today = LocalDate.now();
            endDate = today;
            startDate = today.minusDays(6);
        } else {
            // 输入了开始时间和结束时间
            endDate = tempsDto.getEndTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
            startDate = tempsDto.getStartTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        }

        // 构建日期列表
        List<Date> dates = new ArrayList<>();
        for (LocalDate date = startDate; !date.isAfter(endDate); date = date.plusDays(1)) {
            dates.add(Date.from(date.atStartOfDay(ZoneId.systemDefault()).toInstant()));
        }
        tempDto.setTime(dates);
        List<String> names = new ArrayList<>();
        List<Category> categoryList = new ArrayList<>();

            //室外温度曲线
            Category category1 = new Category();
            //小区名称
            category1.setName("平均室外温度");
            category1.setType("line");
            category1.setData(new ArrayList<>());

            for (Date date : dates) {
                Map<String, Object> params = new HashMap<>();
                String formattedDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate().toString();
                params.put("date", formattedDate);

                Long temperature = weatherMapper.selectWeatherListByTimes(params);
                if (temperature != null) {
                    category1.getData().add(temperature);
                } else {
                    category1.getData().add(0l);
                }
            }
            categoryList.add(category1);
        //当传参不为空时
        if (nameList!=null&&nameList.size()>0){
            for (String name : nameList) {
                //小区名称
                names.add(name);

                Category category = new Category();
                //小区名称
                category.setName(name);
                category.setType("line");
                category.setData(new ArrayList<>());

                for (Date date : dates) {
                    Map<String, Object> params = new HashMap<>();
                    params.put("name", name);
                    String formattedDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate().toString();
                    params.put("date", formattedDate);

                    Long temperature = equipmentDockingMapper.selectEquipmentCountDockingByTimesName(params);
                    if (temperature != null) {
                        category.getData().add(temperature);
                    } else {
                        category.getData().add(0l);
                    }
                }
                categoryList.add(category);
            }

        }
        names.add("平均室外温度");
        tempDto.setName(names);
        tempDto.setCategoryList(categoryList);


        return tempDto;

    }

    /**
     * 室温分析点击房间后户主历史信息数据
     */
    @Override
    public List<EquipmentDocking> selectEquipmentDockingPersonHistory(RoomNoDto dateDto) {
        //户主房间编号
        String roomNo = dateDto.getRoomNo();
        if (dateDto.getStartTime()==null&&dateDto.getEndTime()==null){
            return equipmentDockingMapper.selectEquipmentCountDockingByRoomss(roomNo);
        }
        return equipmentDockingMapper.selectEquipmentCountDockingByRoomNos(roomNo, dateDto.getStartTime(), dateDto.getEndTime());

    }

    /**
     * 供暖概况室内外曲线（大屏）
     */
    @Override
    public TempDto selectEquipmentDockingStanceById(Long id) {
        TempDto tempDto = new TempDto();
        LocalDate today = LocalDate.now();
        LocalDate startDate = today.minusDays(29);
        List<Date> dates = new ArrayList<>();

        // 构建日期列表
        for (LocalDate date = startDate; !date.isAfter(today); date = date.plusDays(1)) {
            dates.add(Date.from(date.atStartOfDay(ZoneId.systemDefault()).toInstant()));
        }
        tempDto.setTime(dates);
        List<String> names = new ArrayList<>();
        List<Category> categoryList = new ArrayList<>();

        // 室外温度曲线
        Category outdoorCategory = new Category();
        outdoorCategory.setName("平均室外温度");
        outdoorCategory.setType("line");
        outdoorCategory.setData(new ArrayList<>());

        // 批量查询天气数据
        List<Long> outdoorTemperatures = weatherMapper.selectWeatherListByDates(dates);
        for (Long temperature : outdoorTemperatures) {
            outdoorCategory.getData().add(temperature != null ? temperature : 0L);
        }
        categoryList.add(outdoorCategory);

        // 热力站室内温度曲线
        HeatStation heatStation = heatStationMapper.selectHeatStationById(id);
        String stationName = heatStation.getName();
        Category indoorCategory = new Category();
        indoorCategory.setName(stationName);
        indoorCategory.setType("line");
        indoorCategory.setData(new ArrayList<>());

        // 获取该热力站下的所有小区
        List<CommunityInfo> communityList = communityInfoMapper.selectCommunityInfoLists(id);
        List<String> communityNames = communityList.stream()
                .map(CommunityInfo::getName)
                .collect(Collectors.toList());

        // 创建参数 Map
        Map<String, Object> params = new HashMap<>();
        params.put("dates", dates);
        params.put("communityNames", communityNames);

        // 批量查询室内温度
        List<Long> avgTemperatures = equipmentDockingMapper.selectAvgTemperatureByStationAndDates(params);
        for (Long avgTemperature : avgTemperatures) {
            indoorCategory.getData().add(avgTemperature != null ? avgTemperature : 0L);
        }
        categoryList.add(indoorCategory);
        names.add(stationName);

        tempDto.setName(names);
        tempDto.setCategoryList(categoryList);

        return tempDto;
    }
//    @Override
//    public TempDto selectEquipmentDockingStanceById(Long id) {
//        TempDto tempDto = new TempDto();
//
//        LocalDate startDate;
//        LocalDate endDate;
//        // 没有输入开始时间和结束时间，默认查询过去一周的数据
//        LocalDate today = LocalDate.now();
//        endDate = today;
//        startDate = today.minusDays(29);
//
//
//        // 构建日期列表
//        List<Date> dates = new ArrayList<>();
//        for (LocalDate date = startDate; !date.isAfter(endDate); date = date.plusDays(1)) {
//            dates.add(Date.from(date.atStartOfDay(ZoneId.systemDefault()).toInstant()));
//        }
//        tempDto.setTime(dates);
//        List<String> names = new ArrayList<>();
//        List<Category> categoryList = new ArrayList<>();
//
//        //室外温度曲线
//        Category category1 = new Category();
//        //小区名称
//        category1.setName("平均室外温度");
//        category1.setType("line");
//        category1.setData(new ArrayList<>());
//
//        for (Date date : dates) {
//            Map<String, Object> params = new HashMap<>();
//            String formattedDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate().toString();
//            params.put("date", formattedDate);
//
//            Long temperature = weatherMapper.selectWeatherListByTimes(params);
//            if (temperature != null) {
//                category1.getData().add(temperature);
//            } else {
//                category1.getData().add(0l);
//            }
//        }
//        categoryList.add(category1);
//
//        // 2. 热力站室内温度曲线
//        Category indoorCategory = new Category();
//        // 获取热力站信息
//        HeatStation heatStation = heatStationMapper.selectHeatStationById(id);
//        String stationName = heatStation.getName(); // 热力站名称
//        indoorCategory.setName(stationName);
//        indoorCategory.setType("line");
//        indoorCategory.setData(new ArrayList<>());
//
//        // 获取该热力站下的所有小区
//        List<CommunityInfo> communityList = communityInfoMapper.selectCommunityInfoLists(id);
//        List<String> communityNames = communityList.stream()
//                .map(CommunityInfo::getName)
//                .collect(Collectors.toList());
//
//        // 计算每天的平均温度
//        for (Date date : dates) {
//            Map<String, Object> params = new HashMap<>();
//            String formattedDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate().toString();
//            params.put("date", formattedDate);
//            params.put("communityNames", communityNames);  // 需要修改Mapper支持多个小区名称
//
//            // 修改Mapper方法，计算多个小区的平均温度
//            Long avgTemperature = equipmentDockingMapper.selectAvgTemperatureByStationAndTime(params);
//            indoorCategory.getData().add(avgTemperature != null ? avgTemperature : 0L);
//        }
//        categoryList.add(indoorCategory);
//        names.add(stationName);
//
//        tempDto.setName(names);
//        tempDto.setCategoryList(categoryList);
//
//        return tempDto;
//    }

    @Override
    public List<EquipmentDocking> selectEquipmentDockingListss(EquipmentDocking equipmentDocking) {
        return equipmentDockingMapper.selectEquipmentDockingList(equipmentDocking);
    }

    /**
     * 各个设备数量以及在线率（大屏 设备管理）
     */
    @Autowired
    private HeatInfoMapper heatInfoMapper;
    @Autowired
    private ControlValveMapper controlValveMapper;
    @Override
    public List<Equipment> selectEquipmentDockings() {
        List<Equipment> equipments = new ArrayList<>();
        //户表
        Equipment equipment1 = new Equipment();
        HeatInfo heatInfo1 = new HeatInfo();
        List<HeatInfo> heatInfos = heatInfoMapper.selectHeatInfoList(heatInfo1);
        //户表总数
        long count = heatInfos.stream().filter(heatInfo -> heatInfo.getHistory().equals("1")).count();
        //户表在线数
        long count1 = heatInfos.stream().filter(heatInfo -> heatInfo.getState().equals("0")).count();
        //户表在线率
        double num = (double) count1 / (double) count *100;
        if (count1==0&&count==0){
            equipment1.setProportion("0");
        }else {
            String formattedValue = String.format("%.1f", num);
            equipment1.setProportion(formattedValue);
        }
        equipment1.setName("户用热表");
        equipment1.setCount(count);
        equipment1.setLine(count1);
        equipments.add(equipment1);

        //户用平衡阀
        Equipment equipment2 = new Equipment();
        ControlValve controlValve1 = new ControlValve();
        List<ControlValve> controlValves = controlValveMapper.selectControlValveList(controlValve1);
        //户阀总数
        long count6 = controlValves.stream().filter(controlValve -> controlValve.getType().equals("0")).count();
        //户阀在线数
        long count3 = controlValves.stream().filter(controlValve -> controlValve.getState().equals("0")).filter(controlValve -> controlValve.getType().equals("0")).count();
        //户阀在线率
        Double num2 = (double) count3 / (double) count6 *100;
        String formattedValue1 = String.format("%.1f", num2);
        equipment2.setName("户用平衡阀");
        equipment2.setCount(count6);
        equipment2.setLine(count3);
        equipment2.setProportion(formattedValue1);
        equipments.add(equipment2);

        //户用锁闭阀
        Equipment equipment = new Equipment();
        //户阀总数
        long count8 = controlValves.stream().filter(controlValve -> controlValve.getType().equals("1")).count();
        //户阀在线数
        long count5 = controlValves.stream().filter(controlValve -> controlValve.getState().equals("0")).filter(controlValve -> controlValve.getType().equals("1")).count();
        //户阀在线率
        Double num5 = (double) count5 / (double) count8 *100;
        String formattedValue6 = String.format("%.1f", num5);
        equipment.setName("户用锁闭阀");
        equipment.setCount(count8);
        equipment.setLine(count5);
        equipment.setProportion(formattedValue6);
        equipments.add(equipment);


        //测温
        Equipment equipment3 = new Equipment();
        EquipmentDocking equipmentDocking1 = new EquipmentDocking();
        List<EquipmentDocking> equipmentDockings = equipmentDockingMapper.selectEquipmentDockingList(equipmentDocking1);

        // 获取当前时间
        Date now = new Date();

        // 测温总数
        long count4 = equipmentDockings.size();

        // 测温在线数
        long counts = equipmentDockings.stream().filter(equipmentDocking -> {
            Date uploadTime = equipmentDocking.getUploadtime(); // 假设 getUploadTime() 返回 Date 类型
            if (uploadTime == null) {
                return false; // 如果上传时间为空，则视为不在线
            }
            long diffInMillies = Math.abs(now.getTime() - uploadTime.getTime());
            long diffInHours = TimeUnit.HOURS.convert(diffInMillies, TimeUnit.MILLISECONDS);
            return diffInHours <= 24; // 24 小时之内视为在线
        }).count();

        // 测温在线率
        double num3 = (double) counts / (double) count4 * 100;
        String formattedValue2 = String.format("%.1f", num3);
        equipment3.setName("测温");
        equipment3.setCount(count4);
        equipment3.setLine(counts);
        equipment3.setProportion(formattedValue2);
        equipments.add(equipment3);


//        Equipment equipment3 = new Equipment();
//        EquipmentDocking equipmentDocking1 = new EquipmentDocking();
//        List<EquipmentDocking> equipmentDockings = equipmentDockingMapper.selectEquipmentDockingList(equipmentDocking1);
//        //测温总数
//        long count4 = equipmentDockings.size();
//        //测温在线数
//        long counts = equipmentDockings.stream().filter(equipmentDocking -> equipmentDocking.getDeviceStatus().equals("正常")).count();
//        //测温在线率
//        double num3 = (double) counts / (double) count4 * 100;
//        String formattedValue2 = String.format("%.1f", num3);
//        equipment3.setName("测温");
//        equipment3.setCount(count4);
//        equipment3.setLine(counts);
//        equipment3.setProportion(formattedValue2);
//        equipments.add(equipment3);

        //单元表
        Equipment equipment4 = new Equipment();
        //todo 未确定
        equipment4.setName("单元表");
        equipment4.setCount(0L);
        equipment4.setLine(0L);
        equipment4.setProportion("0");
        equipments.add(equipment4);

        //单元阀
        Equipment equipment5 = new Equipment();
        //单元阀总数
        long count7 = controlValves.stream().filter(controlValve -> controlValve.getType().equals("2")).count();
        //户阀在线数
        long countt = controlValves.stream().filter(controlValve -> controlValve.getState().equals("0")).filter(controlValve -> controlValve.getType().equals("2")).count();
        //户阀在线率
        Double num4 = (double) countt / (double) count7 *100;
        String formattedValue3 = String.format("%.1f", num2);
        equipment5.setName("单元阀");
        equipment5.setCount(count7);
        equipment5.setLine(count7);
        equipment5.setProportion("100");
        equipments.add(equipment5);

        //压力表
        Equipment equipment6 = new Equipment();
        //todo 未确定
        equipment6.setName("压力表");
        equipment6.setCount(0L);
        equipment6.setLine(0L);
        equipment6.setProportion("0");
        equipments.add(equipment6);

        //集抄设备
        Equipment equipment7 = new Equipment();
        //todo 未确定
        equipment7.setName("集抄设备");
        equipment7.setCount(0L);
        equipment7.setLine(0L);
        equipment7.setProportion("0");
        equipments.add(equipment7);


        return equipments;
    }

    @Override
    public List<EquipmentDocking> selectEquipmentDockingPersonHistorys(String roomNo) {

        return equipmentDockingMapper.selectEquipmentCountDockingByRoomss(roomNo);
    }

    /**
     * 查询并拉取黑蚂蚁实时室温数据（除2023对接小区）
     */
    @Override
    public Object selectEquipmentDockingListsss() {
        //获取token值
        String token = null;
        try {
            // 创建URL对象
            URL url = new URL("http://112.33.35.32:2019/api/v1/auth/login");

            // 打开连接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            // 设置请求方法
            conn.setRequestMethod("POST");

            // 设置请求头
            conn.setRequestProperty("Content-Type", "application/json");

            // 启用输入输出流
            conn.setDoOutput(true);

            // 创建请求数据
            String jsonInputString = "{\"name\":\"api_bdft\",\"password\":\"123456\"}";

            // 写入请求数据
            try (OutputStream os = conn.getOutputStream()) {
                byte[] input = jsonInputString.getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            // 获取响应
            int code = conn.getResponseCode();
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            StringBuilder response = new StringBuilder();
            String responseLine;
            while ((responseLine = br.readLine()) != null) {
                response.append(responseLine.trim());
            }

            // 解析JSON响应
            JSONObject jsonResponse = new JSONObject(response.toString());
            if (jsonResponse.getInt("code") == 200) {
                token = jsonResponse.getJSONObject("data").getStr("token");
                System.out.println("Token:" + token);
            } else {
                System.out.println("Error: " + jsonResponse.getStr("message"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        String host = "http://112.33.35.32:2019";
        String path = "/api/v1/data/th/realtime";
        String method = "GET";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        //根据API的要求，定义相对应的Content-Type
        // 添加Authorization token到headers
//        String token = "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJ1c2VyX2JkZnRybHpqIiwiY3JlYXRlZCI6MTcyMTY5ODY0ODAwNSwiZXhwIjoxNzIyMzAzNDQ4fQ.4hvpyEEdC0qUaRx8B148L7JW2PtHzaR8U0A5iyGbENii-DpXw0D3g3PT2EICV1lWhRSQm4mGvn9pnQetowomkg";  // 替换为��的实际token
        headers.put("Authorization", "Bearer " + token);
          Map<String, String> querys = new HashMap<String, String>();
        querys.put("page", "1");
        querys.put("pageSize", "-1");
//        querys.put("onlineState", "2");
        querys.put("sortProp", "uploadtime");
        querys.put("sortOrder", "1");
        Object result = new Object();
        try {

            HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
//            System.out.println(response.toString());
            //获取response的body
            result = EntityUtils.toString(response.getEntity());
            System.out.println(result);
//            this.insertEquipmentDockingList(result);

        } catch (Exception e) {
            e.printStackTrace();
        }
//        return "操作成功！";
        return result;
    }

    /**
     * 获取温度数据(饼状图）
     * @return
     */
    @Override
    public Map<String, Object> getTemperatureData() {
        Map<String, Integer> counts = equipmentDockingMapper.selectTemperatureCounts();

        // 准备响应数据
        Map<String, Object> cdata = new HashMap<>();
        cdata.put("xData", List.of("18°C以下", "18°C-20°C", "20°C-24°C", "24°C以上"));
        cdata.put("seriesData", List.of(
                Map.of("value", counts.get("below18"), "name", "18°C以下"),
                Map.of("value", counts.get("between18And20"), "name", "18°C-20°C"),
                Map.of("value", counts.get("between20And24"), "name", "20°C-24°C"),
                Map.of("value", counts.get("above24"), "name", "24°C以上")
        ));

        return cdata;

    }


//    @Override
//    public List<AvgTempDto> getAvgTempByTimeRange(TempExportRequestDto requestDto) {
//        String startTime;
//        String endTime;
//        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
//        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//
//        if (requestDto == null || StringUtils.isEmpty(requestDto.getStartTime()) || StringUtils.isEmpty(requestDto.getEndTime())) {
//            // 如果没有传入时间范围，使用默认的昨天到今天
//            LocalDate yesterday = LocalDate.now().minusDays(1);
//            LocalDate today = LocalDate.now();
//
//            startTime = yesterday.atStartOfDay().format(dateTimeFormatter);  // 昨天 00:00:00
//            endTime = today.atStartOfDay().format(dateTimeFormatter);       // 今天 00:00:00
//        } else {
//            // 使用传入的日期范围
//            LocalDate startDate = LocalDate.parse(requestDto.getStartTime(), dateFormatter);
//            LocalDate endDate = LocalDate.parse(requestDto.getEndTime(), dateFormatter);
//
//            // 开始时间为选择的开始日期的 00:00:00
//            startTime = startDate.atStartOfDay().format(dateTimeFormatter);
//            // 结束时间为选择的结束日期的下一天的 00:00:00
//            endTime = endDate.plusDays(1).atStartOfDay().format(dateTimeFormatter);
//        }
//
//        // 调用 Mapper 查询数据
//        return equipmentDockingMapper.selectAvgTempByTimeRange(startTime, endTime);
//    }
//@Override
//public List<AvgTempDto> getAvgTempByTimeRange(TempExportRequestDto requestDto) {
//    String startTime;
//    String endTime;
//    DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
//    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//
//    if (requestDto == null || StringUtils.isEmpty(requestDto.getStartTime()) || StringUtils.isEmpty(requestDto.getEndTime())) {
//        // 如果没有传入时间范围，使用默认的前一天
//        LocalDate yesterday = LocalDate.now().minusDays(1);
//        startTime = yesterday.atStartOfDay().format(dateTimeFormatter);  // 昨天 00:00:00
//        endTime = yesterday.atStartOfDay().plusDays(1).format(dateTimeFormatter); // 昨天 23:59:59
//    } else {
//        // 使用传入的日期范围
//        LocalDate startDate = LocalDate.parse(requestDto.getStartTime(), dateFormatter);
//        LocalDate endDate = LocalDate.parse(requestDto.getEndTime(), dateFormatter);
//
//        // 开始时间为选择的开始日期的 00:00:00
//        startTime = startDate.atStartOfDay().format(dateTimeFormatter);
//        // 结束时间为选择的结束日期的下一天的 00:00:00
//        endTime = endDate.plusDays(1).atStartOfDay().format(dateTimeFormatter);
//    }
//
//    // 调用 Mapper 查询数据
//    return equipmentDockingMapper.selectAvgTempByTimeRange(startTime, endTime);
//}
public List<AvgTempDto> getAvgTempByTimeRange(TempExportRequestDto requestDto) {
    String startTime;
    String endTime;
    DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    if (requestDto == null || requestDto.getStartTime() == null || requestDto.getEndTime() == null) {
        // 默认导出前一天的平均温度
        LocalDate yesterday = LocalDate.now().minusDays(1);
        startTime = yesterday.atStartOfDay().format(dateTimeFormatter);
        endTime = yesterday.atStartOfDay().plusDays(1).format(dateTimeFormatter);
    } else {
        // 使用传入的日期范围
        LocalDate startDate = LocalDate.parse(requestDto.getStartTime(), dateFormatter);
        LocalDate endDate = LocalDate.parse(requestDto.getEndTime(), dateFormatter);
        startTime = startDate.atStartOfDay().format(dateTimeFormatter);
        endTime = endDate.plusDays(1).atStartOfDay().format(dateTimeFormatter);
    }

    // 调用 Mapper 查询数据
    return equipmentDockingMapper.selectAvgTempByTimeRange(startTime, endTime, requestDto.getVillageNames());
}

    /**
     * 获取最高室温数据
     * @return
     */
    @Override
    public List<EquipmentDocking> selectEquipmentDockingMax() {

        List<EquipmentDocking> equipmentDockingList = equipmentDockingMapper.selectEquipmentDockingListMax();
        for (EquipmentDocking docking : equipmentDockingList) {
            EquipmentDocking temp=equipmentDockingMapper.selectEquipmentDockingTemp(docking.getRoomNo());
            if (temp!=null){
                docking.setAverageTemperature(temp.getAverageTemperature());
                docking.setMaxTem(temp.getMaxTem());
                docking.setMinTem(temp.getMinTem());
            }
            //采暖方式与户型赋值
            RoomInfo roomInfo = roomInfoMapper.selectRoomInfoByRoomNo(docking.getRoomNo());
            docking.setHeatWay(roomInfo.getHeatWay());
            docking.setHomeType(roomInfo.getHomeType());
            //热力站与机组赋值
            Long communityId = roomInfo.getCommunityId();
            CommunityInfo communityInfo = communityInfoMapper.selectCommunityInfoById(communityId);
            Long heatId = communityInfo.getHeatId();
            HeatStation heatStation = heatStationMapper.selectHeatStationById(heatId);
            docking.setHeatName(heatStation.getName());
            docking.setCrew(heatStation.getCrew());

        }
        return equipmentDockingList;
    }

    /**
     * 获取最低室温数据
     * @return
     */
    @Override
    public List<EquipmentDocking> selectEquipmentDockingMin() {
        List<EquipmentDocking> equipmentDockingList = equipmentDockingMapper.selectEquipmentDockingListMin();
        for (EquipmentDocking docking : equipmentDockingList) {
            EquipmentDocking temp=equipmentDockingMapper.selectEquipmentDockingTemp(docking.getRoomNo());
            if (temp!=null){
                docking.setAverageTemperature(temp.getAverageTemperature());
                docking.setMaxTem(temp.getMaxTem());
                docking.setMinTem(temp.getMinTem());
            }
            //采暖方式与户型赋值
            RoomInfo roomInfo = roomInfoMapper.selectRoomInfoByRoomNo(docking.getRoomNo());
            docking.setHeatWay(roomInfo.getHeatWay());
            docking.setHomeType(roomInfo.getHomeType());
            //热力站与机组赋值
            Long communityId = roomInfo.getCommunityId();
            CommunityInfo communityInfo = communityInfoMapper.selectCommunityInfoById(communityId);
            Long heatId = communityInfo.getHeatId();
            HeatStation heatStation = heatStationMapper.selectHeatStationById(heatId);
            docking.setHeatName(heatStation.getName());
            docking.setCrew(heatStation.getCrew());
        }
        return equipmentDockingList;
    }

    @Override
    public List<EquipmentDocking> selectEquipmentDockingByRoomNos(String[] roomNos) {
        return equipmentDockingMapper.selectEquipmentDockingByRoomNos(roomNos);
    }


}
